<?php
/*
 * This file is part of EC-CUBE
 *
 * Copyright(c) 2000-2012 LOCKON CO.,LTD. All Rights Reserved.
 *
 * http://www.lockon.co.jp/
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

// {{{ requires
require_once CLASS_EX_REALDIR . 'page_extends/LC_Page_Ex.php';
require_once CLASS_REALDIR . 'pages/pay/CallerService.php';

/**
 * 会員登録のページクラス.
 *
 * @package Page
 * @author LOCKON CO.,LTD.
 * @version $Id: LC_Page_Regist.php 21950 2012-07-02 11:42:51Z pineray $
 */
class LC_Page_Pay extends LC_Page_Ex {

    // {{{ properties

    // }}}
    // {{{ functions
	
    /**
     * Page を初期化する.
     *
     * @return void
     */
    function init() {
    	
        parent::init();
        $this->tpl_mainpage = 'pay/index.tpl';
        //$this->linkCss[] = 'css/datepickerImport.css';
        $this->linkCss[] = 'css/sapaImport.css';
        //引入本页面javascript
	    $this->link_javascript[] = "js/sapa/jquery.dataTables.js";
        $this->link_javascript[] = "js/sapa/jquery.ui.core.js";
        //$this->link_javascript[] = "js/sapa/jquery.ui.datepicker.js";
        $this->link_javascript[] = "js/sapa/jquery.ui.widget.js";
        
    }

    /**
     * Page のプロセス.
     *
     * @return void
     */
    function process() {
        parent::process();
        $this->action();
        $this->sendResponse();
       
    }

    /**
     * Page のAction.
     *
     * @return void
     */
    function action() {
    	
        switch ($this->getMode()) {
            case 'order':
            	$this->doPaypalTransaction();
                break;
                
            case 'error':
            	
            	//$this->deleteRegistedData();
            	$this->resArray=$_SESSION['reshash']; 
			 	$this->errorCode= $_SESSION['curl_error_no'];
				$this->errorMessage=$_SESSION['curl_error_msg'];
				$this->tpl_mainpage ='pay/error.tpl';
                break;
            case 'cancel':  
            	//$this->deleteRegistedData(); 
            	$this->tpl_mainpage ='pay/cancel.tpl';
            	
                break;
            case 'complete':
            	// 写log
				$this->writePayMentLog();
            	
            	$payMode = $this->objSess->GetSession('payMode');
            	if($payMode =="membershipFee"){
            		
            		//注册正式会员 并发送邮件
            		$this->tobeAReallyMember();
            		//写入付费明细表
            		$this->putPaymentInfoToDb();
            	}elseif ($payMode =="conferencePay"){
					
            		//写入会议参加者信息表
            		$this->joinConference();
            		//写入付费明细表
            		$this->putPaymentInfoToDb();
            		//发送邮件
            	}else{
            		//GC_Utils_Ex::gfPrintLog($logStr);
            	}
            	$this->tpl_mainpage ='pay/complete.tpl';
                break;
            
            case 'payInfoConfirm':
            	$this->serviceInfo = $this->objSess->GetSession('payInfoArr');
    			$this->amountCount = $this->objSess->GetSession('amountCount');
            	
                break;
                
            default:
            	SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'accese error.');
                break;
        }
    }

    /**
     * デストラクタ.
     *
     * @return void
     */
    function destroy() {
        parent::destroy();
    }
	/**
	 * 
	 * Enter description here ...
	 */
	function doPaypalTransaction(){
		$token = $_REQUEST['token'];
		if(! isset($token)) {
				
			   $serverName = $_SERVER['SERVER_NAME'];
			   $serverPort = $_SERVER['SERVER_PORT'];
			   $url=dirname('http://'.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']);
	
				//币种 美元
			   $currencyCodeType='USD';
			   //模式
			   $paymentType='Sale';
			   $returnURL =urlencode($url.'/index.php?currencyCodeType='.$currencyCodeType.'&paymentType='.$paymentType.'&mode=order');
			   $cancelURL =urlencode("$url/index.php?paymentType=$paymentType".'&mode=cancel');
			
			$nvpstr = $this->getParPoststr();
			$nvpstr .= "&CALLBACKTIMEOUT=4&";
			$nvpstr .= "ReturnUrl=".$returnURL;
			$nvpstr .= "&CANCELURL=".$cancelURL ;
			$nvpstr .= "&CURRENCYCODE=".$currencyCodeType;
			$nvpstr .= "&PAYMENTACTION=".$paymentType;
			   
	        $nvpstr = $nvpHeader.$nvpstr;
	        
		 	/* Make the call to PayPal to set the Express Checkout token
			If the API call succeded, then redirect the buyer to PayPal
			to begin to authorize payment.  If an error occured, show the
			resulting errors
			*/
		   	$resArray=hash_call("SetExpressCheckout",$nvpstr);
		   	
		   	$_SESSION['reshash']=$resArray;

			$ack = strtoupper($resArray["ACK"]);
			
			   if($ack=="SUCCESS"){
						// Redirect to paypal.com here
						$token = urldecode($resArray["TOKEN"]);
						$payPalURL = PAYPAL_URL.$token;
						header("Location: ".$payPalURL);
					  } else  {
						 	//Redirecting to APIError.php to display errors.
						 	$this->resArray=$_SESSION['reshash']; 
						 	$this->errorCode= $_SESSION['curl_error_no'];
							$this->errorMessage=$_SESSION['curl_error_msg'];
							
							//SC_Response_Ex::sendRedirect(HTTP_URL."pay/cancel.php");
							SC_Response_Ex::sendRedirect(HTTP_URL."pay/index.php?mode=error");
						}
		} else {
				 /* At this point, the buyer has completed in authorizing payment
					at PayPal.  The script will now call PayPal with the details
					of the authorization, incuding any shipping information of the
					buyer.  Remember, the authorization is not a completed transaction
					at this state - the buyer still needs an additional step to finalize
					the transaction
					*/
				   $token =urlencode( $_REQUEST['token']);
		
				 /* Build a second API request to PayPal, using the token as the
					ID to get the details on the payment authorization
					*/
				   $nvpstr="&TOKEN=".$token;
		
				   $nvpstr = $nvpHeader.$nvpstr;
				 /* Make the API call and store the results in an array.  If the
					call was a success, show the authorization details, and provide
					an action to complete the payment.  If failed, show the error
					*/
				   $resArray=hash_call("GetExpressCheckoutDetails",$nvpstr);
				   //$_SESSION['reshash']=$resArray;
				   $ack = strtoupper($resArray["ACK"]);
					
				   if($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING'){
							//require_once "GetExpressCheckoutDetails.php";
							$token = urlencode($_REQUEST['token']);
							$payerID = urlencode($_REQUEST['PayerID']);
							$paymentAmount = $resArray['AMT'] + $resArray['SHIPDISCAMT'];
							$_SESSION['paymentAmount']=$_REQUEST['paymentAmount'];
							$currCodeType = urlencode($_REQUEST['currencyCodeType']);
							$paymentType = urlencode($_REQUEST['paymentType']);
							
							ini_set('session.bug_compat_42',0);
							ini_set('session.bug_compat_warn',0);
							$serverName = urlencode($_SERVER['SERVER_NAME']);
							
							$nvpstr='&TOKEN='.$token.'&PAYERID='.$payerID.'&PAYMENTACTION='.$paymentType.'&AMT='.$paymentAmount.'&CURRENCYCODE='.$currCodeType.'&IPADDRESS='.$serverName ;
							
							 /* Make the call to PayPal to finalize payment
							    If an error occured, show the resulting errors
							    */
							$resArray=hash_call("DoExpressCheckoutPayment",$nvpstr);
							
							/* Display the API response back to the browser.
							   If the response from PayPal was a success, display the response parameters'
							   If the response was an error, display the errors received using APIError.php.
							   */
							$ack = strtoupper($resArray["ACK"]);
							
							
							if($ack != 'SUCCESS' && $ack != 'SUCCESSWITHWARNING'){
								$_SESSION['reshash']=$resArray;
								//$location = "APIError.php";
								//header("Location: $location");
								
								SC_Response_Ex::sendRedirect(HTTP_URL."pay/index.php?mode=error");
							}
							
							SC_Response_Ex::sendRedirect(HTTP_URL."pay/index.php?mode=complete");
					  } else  {
						//Redirecting to APIError.php to display errors.
						//$location = "APIError.php";
						//header("Location: $location");
						SC_Response_Ex::sendRedirect(HTTP_URL."pay/index.php?mode=error");
					  }
		}
	}

	function tobeAReallyMember(){
		//$userId = $this->objSess->GetSession('regist_userId');
		$userId = $_SESSION['regist_userId'];
		
		if(!empty($userId)){
			$objQuery = SC_Query::getSingletonInstance();
			$mstRs = $objQuery->select('*','temp_mst_users', 'id= ?',array($userId));
			$tabRs = $objQuery->select('*','temp_tab_person_users', 'id= ?',array($userId));
			
			//数据不存在报错
			if (count($mstRs) != 1 || count($tabRs) != 1){
				SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'system error please contact the administrator.');
			}
			//会员会费金额不对报错
			//终身会员
			if($mstRs[0]['member_flg'] == 200){
				$mstRs[0]['paymented_date'] = '2999-01-01 00:00:00';
			//一般年会员
			}elseif ($mstRs[0]['member_flg'] == 30){
				$mstRs[0]['paymented_date'] = date("Y-m-d H:i:s",strtotime("+1 year"));
			//学生年会员
			}elseif ($mstRs[0]['member_flg'] == 15){
				$mstRs[0]['paymented_date'] = date("Y-m-d H:i:s",strtotime("+1 year"));
			}else{
				SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'Membership Fee is Incorrect.');
			}
			unset($mstRs[0]['id']);
			$mstRs[0]['status'] = '2';
			$mstRs[0]['create_time'] = 'now()';
			$mstRs[0]['update_time'] = 'now()';
			
			$objQuery->begin();
			$objQuery->insert('mst_users', $mstRs[0]);
			$insertedId = $objQuery->select('LAST_INSERT_ID() AS id','mst_users');
			$this->insertedMstUsrId  = $insertedId[0]['id'];
			
			$tabRs[0]['id'] = $this->insertedMstUsrId;
			$tabRs[0]['create_time'] = 'now()';
			$tabRs[0]['update_time'] = 'now()';
			$objQuery->insert('tab_person_users', $tabRs[0]);
			
			//插入数据库时 出错了	
			if ($objQuery->isError()) {
				$objQuery->rollback();
				SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'system error please contact the administrator.');
				
			}else{
				$objQuery->commit();
			}
			
			//注册成功 发送邮件
			$this->sendRegistMail($this->insertedMstUsrId);
			
		}else{
			SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'system error please contact the administrator.');
		}
	}

    function getServiceInfoFromSession(){
    	$serviceInfo = $this->objSess->GetSession('payInfoArr');
    	
    	$amountCount = 0;
    	//$this->serviceInfo = $this->objSess->GetSession('payInfoArr');
    	if(empty($serviceInfo)){
    		SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'Sessione Order data is error .');
    	}
    	
    	foreach ($serviceInfo as $value) {
    		$value['amountTotal'] = $value['price'] *$value['quantity'];
    		$amountCount+=$value['amountTotal'];
    		$this->serviceInfo[] = $value;
    		$this->amountCount = $amountCount;
    	}
    	//$this->serviceInfo = $serviceInfo;
    	$this->amountCount = $amountCount;
    }
    
    
    function getParPoststr(){
    	$retrunStr = "";
    	$serviceInfoArr = $this->objSess->GetSession('payInfoArr');
    	
    	if(empty($serviceInfoArr)){
    		SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'Sessione Order data is error .');
    	}
    	
    	$serviceName = "";
    	$price = "";
    	$quantity = "";
    	
    	foreach ($serviceInfoArr as $index=>$value) {
    		$serviceName .= '&L_NAME'.$index .'='. $value['serviceName'];
			$price.= '&L_AMT'.$index .'='.$value['price'];
			$quantity.='&L_QTY'.$index.'='. $value['quantity'];
    	}
    	
		$amt = $this->objSess->GetSession('amountCount');
		$maxamt= $amt+25.00;
		
		$retrunStr .=$serviceName;
		$retrunStr .=$price;
		$retrunStr .=$quantity; 
		$retrunStr .= "&MAXAMT=".(string)$maxamt;
		$retrunStr .= "&AMT=".(string)$amt;
		$retrunStr .= "&ITEMAMT=".(string)$amt;

		return $retrunStr;
    }
    
    function writePayMentLog(){
		$serviceInfoArr = $this->objSess->GetSession('payInfoArr');
    	
		$payMode = $this->objSess->GetSession('payMode');
		
		//$userId = "";
		$email = "";
		$lastname = "";
		$firstname = "";
		$middlename = "";
		
		if($payMode == 'membershipFee' ){
			$registUserId = $_SESSION['regist_userId'];
			$objQuery = SC_Query::getSingletonInstance();
			$mstRs = $objQuery->select('*','temp_mst_users', 'id= ?',array($registUserId));
			$tabRs = $objQuery->select('*','temp_tab_person_users', 'id= ?',array($registUserId));
			
			//$userId = $this->objSess->GetSession('user_id');
			$email = $mstRs[0]['user_email'];
			$lastname = $tabRs[0]['lastname'];
			$firstname = $tabRs[0]['firstname'];
			$middlename = $tabRs[0]['middlename'];
		}else if($payMode == 'conferencePay'){
			//$userId = $this->objSess->GetSession('user_id');
			$email = $this->objSess->GetSession('user_email');
			$lastname = $this->objSess->GetSession('lastname');
			$firstname = $this->objSess->GetSession('firstname');
			$middlename = $this->objSess->GetSession('middlename');
		}
		$sid = $this->objSess->GetSID();
		
        
        $logStr  = "payment success";
        $logStr .= " " .$payMode; 
        //$logStr .= " " .$userId;
        $logStr .= " " .$email;
        $logStr .= " " .$firstname;
        $logStr .= " " .$middlename;
        $logStr .= " " .$lastname;
        //$logStr .= " " .$sid;
        
    	foreach ($serviceInfoArr as $index=>$value) {
    		$logStr .= ' ServiceName: '. $value['serviceName'];
			$logStr .= ' price: '.$value['price'].'$';
			$logStr .= ' quantity: '. $value['quantity'];
    	}
    	//paypal存在session里的付费金额
    	$amt = $this->objSess->GetSession('paymentAmount');
    	//交易ID
    	GC_Utils_Ex::gfPrintLog($logStr." AmountCount:".$amt."$ ".date("Y-m-d H:i:s"));
    }
    
    function putPaymentInfoToDb(){
    	$serviceInfoArr = $this->objSess->GetSession('payInfoArr');
    	
		$payMode = $this->objSess->GetSession('payMode');
		
		
		
		if($payMode == 'membershipFee' ){
			//$registUserId = $this->insertedMstUsrId;
			//$objQuery = SC_Query::getSingletonInstance();
			//$mstRs = $objQuery->select('*','temp_mst_users', 'id= ?',array($registUserId));
			//$tabRs = $objQuery->select('*','temp_tab_person_users', 'id= ?',array($registUserId));
			
			$payDetailArr = $this->getInsPayDetailArr();
			$payDetailArr['user_id'] = $this->insertedMstUsrId;
			$payDetailArr['goods_type'] = "0";
			$payDetailArr['goods_id'] = $serviceInfoArr[0]['price']; 
			$payDetailArr['goods_name'] = $serviceInfoArr[0]['serviceName'];
			$payDetailArr['price'] = $serviceInfoArr[0]['price'];
			$payDetailArr['quantity'] = $serviceInfoArr[0]['quantity'];
			$payDetailArr['amount'] = $this->objSess->GetSession('amountCount');
			
			//插入数据库
			$this->indertIntoPayDetail($payDetailArr);
		}else if($payMode == 'conferencePay'){
			
			$payDetailArr = $this->getInsPayDetailArr();
			$payDetailArr['user_id'] =$this->objSess->GetSession('user_id');
			$conferenceId = $this->objSess->GetSession('joinConferenceId');
			$payDetailArr['goods_type'] = "CF".str_pad($conferenceId,8,"*",STR_PAD_LEFT);
			
			foreach ($serviceInfoArr as $index=>$value) {
				
	    		$payDetailArr['goods_id'] = "SF".str_pad($value['feeId'],8,"*",STR_PAD_LEFT);
	    		$payDetailArr['goods_name'] =$value['serviceName'];
	    		$payDetailArr['price'] =$value['price'];
	    		$payDetailArr['quantity'] =$value['quantity'];
	    		$payDetailArr['amount'] = $value['price']* $value['quantity'];
	    		
	    		//插入数据库
	    		$this->indertIntoPayDetail($payDetailArr);
	    	}
				
		}
		
		
    }
    
    function getInsPayDetailArr(){
    	$payDetailArr = array();
    	$payDetailArr['pay_kind'] = "PAYPAL";
		$payDetailArr['pay_date'] = "NOW()";
		$payDetailArr['del_flg'] = "0";
		$payDetailArr['create_time'] = "NOW()";
		$payDetailArr['update_time'] = "NOW()";
		
		return $payDetailArr;
    }
    function indertIntoPayDetail($insetArr){
    	$objQuery = SC_Query::getSingletonInstance();
        $objQuery->begin();
        $objQuery->insert('tab_pay_detail',$insetArr);
        //操作数据库出错
    	if ($objQuery->isError){
    		$objQuery->rollback();
    		SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, "Update DB error,please contact with administrator");
    	}else{
    		$objQuery->commit();
    	} 
    }
    
    function joinConference(){
    	$joinInfoArr = $this->objSess->GetSession("joinInfoArr");
    	
    	if(!empty($joinInfoArr)){
    		$objQuery = SC_Query::getSingletonInstance();
	        $objQuery->begin();
	        $objQuery->insert('tab_conference_participant',$joinInfoArr);
	        //操作数据库出错
	    	if ($objQuery->isError){
	    		$objQuery->rollback();
	    		SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, "Update DB error,please contact with administrator");
	    	}else{
	    		$objQuery->commit();
	    	} 
    	}
    }
}
